package com.lagou.service.impl;

import com.lagou.mapper.CodeMapper;
import com.lagou.pojo.AuthCode;
import com.lagou.service.LocalCodeService;
import com.lagou.service.MailService;
import org.apache.dubbo.config.annotation.Reference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.concurrent.ThreadLocalRandom;

/**
 * @ClassName LocalCodeServiceImpl
 * @Description
 * @Author playboy
 * @Date 2021/7/11 10:30 上午
 * @Version 1.0
 **/
@Service
@Transactional
public class LocalCodeServiceImpl implements LocalCodeService {
	private static Logger log = LoggerFactory.getLogger(LocalCodeServiceImpl.class);

	@Reference
	private MailService emailService;

	@Autowired
	private CodeMapper codeMapper;

	/**
	 * 1.生成code
	 * 2.添加到数据库中
	 * 3.将code发送给指定邮件
	 *
	 * @param email
	 * @return
	 */
	@Override
	public boolean create(String email) {
		//生成随机数
		Integer code = ThreadLocalRandom.current().nextInt(100000, 999999);
		AuthCode authCode = new AuthCode();
		authCode.setEmail(email);
		authCode.setCode(code.toString());
		//当前时间
		Date now = new Date();
		//十分钟后的过期时间
		//Date expire = new Date(now.getTime() + 600000);
		//为了测试改为十秒钟的过期时间
		Date expire = new Date(now.getTime() + 20000);
		authCode.setCreatetime(now);
		authCode.setExpiretime(expire);

		codeMapper.insert(authCode);
		return emailService.email(email, code.toString());
	}
}
